﻿using IOA.MES.Business;
using IOA.MES.Common;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    public class CommonController : Controller
    {
        private ILogger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 获取Ftp图片
        /// </summary>
        public FileResult GetImage(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return File(Encoding.UTF8.GetBytes("文件地址为空"), "text/html; charset=utf-8");
            }
            try
            {
                var buffer = new FtpUtils(Convert.ToString(ConfigurationManager.AppSettings["FtpUserName"]), Convert.ToString(ConfigurationManager.AppSettings["FtpPassword"]))
                .Download(url);
                return File(buffer, $"image/{url.Substring(url.LastIndexOf(".") + 1)}");
            }
            catch (Exception ex)
            {
                return File(Encoding.UTF8.GetBytes("文件下载失败"), "text/html; charset=utf-8");
            }
        }

        /// <summary>
        /// 获取Ftp图片
        /// </summary>
        public FileResult Download(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return File(Encoding.UTF8.GetBytes("文件地址为空"), "text/html; charset=utf-8");
            }

            string ftpUserName = Convert.ToString(ConfigurationManager.AppSettings["FtpUserName"]),
                ftpPassword = Convert.ToString(ConfigurationManager.AppSettings["FtpPassword"]);
            try
            {
                var buffer = new FtpUtils(ftpUserName, ftpPassword)
                .Download(url);
                return File(buffer, "application/octet-stream", url.Substring(url.LastIndexOf("/") + 1));
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"下载文件失败，ftpUserName：{ftpUserName}，ftpPassword：{ftpPassword}，url：{url}");
                return File(Encoding.UTF8.GetBytes("文件下载失败"), "text/html; charset=utf-8");
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        [HttpPost]
        public JsonResult Upload()
        {
            var filePath = Convert.ToString(Request.QueryString["fileName"]);
            if (Request.Files.Count <= 0)
            {
                return Json(new ResultJson<object>(500, "上传的文件为空"));
            }
            else if (string.IsNullOrWhiteSpace(filePath))
            {
                return Json(new ResultJson<object>(500, "filePath为空"));
            }

            var file = Request.Files[0];
            var tmpDirectory = filePath.Substring(0, filePath.LastIndexOf("/"));
            string ftpRoot = Convert.ToString(ConfigurationManager.AppSettings["Ftp"]),
                ftpUserName = Convert.ToString(ConfigurationManager.AppSettings["FtpUserName"]),
                ftpPassword = Convert.ToString(ConfigurationManager.AppSettings["FtpPassword"]);
            try
            {
                var ftp = new FtpUtils(ftpRoot, ftpUserName, ftpPassword);
                ftp.CheckAndCreateDirectory(tmpDirectory);

                var buffer = new byte[file.InputStream.Length];
                file.InputStream.Position = 0;
                file.InputStream.Read(buffer, 0, buffer.Length);
                ftp.Upload(buffer, filePath);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"上传文件失败，ftpRoot：{ftpRoot}，ftpUserName：{ftpUserName}，ftpPassword：{ftpPassword}，tmpDirectory：{tmpDirectory}");
                return Json(new ResultJson<object>(500, $"保存文件出错"));
            }

            return Json(new ResultJson<object>(new
            {
                AbsolutePath = $"{Convert.ToString(ConfigurationManager.AppSettings["Ftp"])}{filePath}"
            }));
        }

        /// <summary>
        /// 查询订单号/工单号
        /// </summary>
        [HttpGet]
        public JsonResult QueryOrderNos(int noType, string workshopCode, string key, DateTime? startTime, DateTime? endTime)
        {
            var nos = new WorkOrderMgr().QueryNos(noType, workshopCode, key, startTime, endTime);
            return Json(new ResultJson<object>(nos), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取相邻班次
        /// </summary>
        [HttpGet]
        public JsonResult GetSideDutyTime(string timeRange, bool isNextDuty)
        {
            var startTime = DateTime.MinValue;
            var endTime = DateTime.MinValue;
            if (string.IsNullOrWhiteSpace(timeRange))
            {
                //返回当前班次
                var result = GetCurrentDuty();
                startTime = result.Item1;
                endTime = result.Item2;
                return Json(new { TimeRange = $"{startTime.ToString("yyyy-MM-dd HH:mm:ss")} 至 {endTime.ToString("yyyy-MM-dd HH:mm:ss")}" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                try
                {
                    startTime = DateTime.Parse(timeRange.Split('至')[0].Trim());
                    endTime = DateTime.Parse(timeRange.Split('至')[1].Trim());
                }
                catch
                {
                    //返回当前班次
                    var result = GetCurrentDuty();
                    startTime = result.Item1;
                    endTime = result.Item2;
                    return Json(new { TimeRange = $"{startTime.ToString("yyyy-MM-dd HH:mm:ss")} 至 {endTime.ToString("yyyy-MM-dd HH:mm:ss")}" }, JsonRequestBehavior.AllowGet);
                }
            }

            if (!isNextDuty)
            {
                //上一班次
                if (startTime.TimeOfDay >= new TimeSpan(20, 45, 0))
                {
                    endTime = startTime.Date.AddHours(20.75);
                }
                else if (startTime.TimeOfDay >= new TimeSpan(8, 45, 0))
                {
                    endTime = startTime.Date.AddHours(8.75);
                }
                else
                {
                    endTime = startTime.Date.AddDays(-1).AddHours(20.75);
                }
                startTime = endTime.AddHours(-12);
            }
            else
            {
                //下一班次
                if (endTime.TimeOfDay <= new TimeSpan(8, 45, 0))
                {
                    startTime = endTime.Date.AddHours(8.75);
                }
                else if (endTime.TimeOfDay <= new TimeSpan(20, 45, 0))
                {
                    startTime = endTime.Date.AddHours(20.75);
                }
                else
                {
                    startTime = endTime.Date.AddDays(1).AddHours(8.75);
                }
                endTime = startTime.AddHours(12);
            }
            return Json(new { TimeRange = $"{startTime.ToString("yyyy-MM-dd HH:mm:ss")} 至 {endTime.ToString("yyyy-MM-dd HH:mm:ss")}" }, JsonRequestBehavior.AllowGet);
        }
        private Tuple<DateTime, DateTime> GetCurrentDuty()
        {
            var startTime = DateTime.MinValue;
            var endTime = DateTime.MinValue;
            //上一班次
            if (DateTime.Now.TimeOfDay >= new TimeSpan(20, 45, 0))
            {
                startTime = DateTime.Today.AddHours(20.75);
            }
            else if (startTime.TimeOfDay >= new TimeSpan(8, 45, 0))
            {
                startTime = DateTime.Today.AddHours(8.75);
            }
            else
            {
                startTime = DateTime.Today.AddDays(-1).AddHours(20.75);
            }
            endTime = startTime.AddHours(12);
            return new Tuple<DateTime, DateTime>(startTime, endTime);
        }

        /// <summary>
        /// 获取物料信息
        /// </summary>
        [HttpPost]
        public JsonResult GetProduct(string productCode)
        {
            var product = new ProductMgr().GetProduct(productCode.Trim());
            return Json(new ResultJson<object>(product));
        }
    }
}
